import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.filechooser.*;
import javax.swing.event.*;
import java.io.*;

public class FontFrame extends JDialog {
    private WDTMain frame;
    private JLabel label = new JLabel("选择字体：");
    private JComboBox<String> fonts = new JComboBox<>();
    private JLabel label2 = new JLabel("选择样式：");
    private JComboBox<String> style = new JComboBox<>();
    private JLabel label3 = new JLabel("选择大小：");
    private JComboBox<Integer> size = new JComboBox<>();
    private JButton buttonApplyAll = new JButton("应用到所有");
    private JButton buttonApplyNow = new JButton("应用到当前");
    private JButton buttonCustomTTF = new JButton("加载本机 TTF 字体……");
    private JButton buttonCancel = new JButton("取消");
    private JPanel exampleText = new JPanel();
    private JLabel text = new JLabel();
    private Container c = getContentPane();
    private Font currentFont;
    private Font fontBase;
    private boolean isNameAndStyleSettable;
    private void initEvents() {
        if (isNameAndStyleSettable) {
            fonts.addItemListener(new ItemListener() {
                public void itemStateChanged(ItemEvent e) {
                    if (e.getStateChange() == ItemEvent.SELECTED) {
                        String name = (String) fonts.getSelectedItem();
                        currentFont = new Font(name, currentFont.getStyle(), currentFont.getSize());
                        text.setFont(currentFont);
                    }
                }
            });
            style.addItemListener(new ItemListener() {
                public void itemStateChanged(ItemEvent e) {
                    if (e.getStateChange() == ItemEvent.SELECTED) {
                        int index = style.getSelectedIndex();
                        int style = -114514;
                        switch (index) {
                            case 0: style = Font.PLAIN; break;
                            case 1: style = Font.BOLD; break;
                            case 2: style = Font.ITALIC; break;
                            case 3: style = Font.BOLD | Font.ITALIC; break;
                            default: break;
                        }
                        currentFont = new Font(currentFont.getName(), style, currentFont.getSize());
                        text.setFont(currentFont);
                    }
                }
            });
        } else {
            ItemListener listeners[] = fonts.getItemListeners();
            for (ItemListener listener: listeners) fonts.removeItemListener(listener);
            listeners = style.getItemListeners();
            for (ItemListener listener: listeners) style.removeItemListener(listener);
        }
        size.addItemListener(new ItemListener() {
            public void itemStateChanged(ItemEvent e) {
                if (e.getStateChange() == ItemEvent.SELECTED) {
                    Integer size_ = (Integer) size.getSelectedItem();
                    int size = size_;
                    currentFont = currentFont.deriveFont((float) size);
                    text.setFont(currentFont);
                }
            }
        });
        buttonApplyNow.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                ((CodeEdit) frame.getTabPane().getSelectedComponent()).setTextAreaFont(currentFont);
                FontFrame.this.dispose();
            }
        });
        buttonApplyAll.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                int componentCount = frame.getTabPane().componentCount();
                for (int i = 0; i < componentCount; i++) {
                    ((CodeEdit) frame.getTabPane().getComponentAt(i)).setTextAreaFont(currentFont);
                }
                FontFrame.this.dispose();
            }
        });
        buttonCustomTTF.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                JFileChooser chooser = new JFileChooser();
                chooser.setFileFilter(new FileNameExtensionFilter("字体文件（*.ttf）", "ttf"));
                int flag = chooser.showOpenDialog(frame);
                if (flag == JFileChooser.APPROVE_OPTION) {
                    File currentFile = chooser.getSelectedFile();
                    fontBase = FileUtil.loadFont(currentFile.getAbsolutePath(), currentFont.getSize());
                    currentFont = fontBase;
                    fonts.removeAllItems();
                    style.removeAllItems();
                    ItemListener listeners[] = fonts.getItemListeners();
                    for (ItemListener listener: listeners) fonts.removeItemListener(listener);
                    listeners = style.getItemListeners();
                    for (ItemListener listener: listeners) style.removeItemListener(listener);
                    text.setFont(currentFont);
                }
            }
        });
        buttonCancel.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                FontFrame.this.dispose();
            }
        });
    }
    private void initialize() {
        if (isNameAndStyleSettable) {
            GraphicsEnvironment e = GraphicsEnvironment.getLocalGraphicsEnvironment();
            String[] fontNames = e.getAvailableFontFamilyNames();
            for (String fontName : fontNames) {
                fonts.addItem(fontName);
            }
            style.addItem("常规");
            style.addItem("粗体");
            style.addItem("斜体");
            style.addItem("粗体 + 斜体");
        }
        int sizes[] = {8, 9, 10, 11, 12, 14, 16, 18, 20, 22, 24, 26, 28, 36, 48, 72};
        for (int i = 0; i < sizes.length; i++) {
            size.addItem(sizes[i]);
        }
        size.setSelectedItem(currentFont.getSize());
        JPanel north = new JPanel();
        JPanel northWrapper = new JPanel();
        north.setLayout(new FlowLayout());
        north.add(label);
        north.add(fonts);
        northWrapper.setLayout(new BorderLayout());
        northWrapper.add(north, BorderLayout.WEST);
        c.add(northWrapper);
        JPanel center = new JPanel();
        JPanel centerWrapper = new JPanel();
        center.setLayout(new FlowLayout());
        center.add(label2);
        center.add(style);
        centerWrapper.setLayout(new BorderLayout());
        centerWrapper.add(center, BorderLayout.WEST);
        c.add(centerWrapper);
        JPanel south = new JPanel();
        JPanel southWrapper = new JPanel();
        south.setLayout(new FlowLayout());
        south.add(label3);
        south.add(size);
        southWrapper.setLayout(new BorderLayout());
        southWrapper.add(south, BorderLayout.WEST);
        c.add(southWrapper);
        exampleText.setBorder(BorderFactory.createTitledBorder(BorderFactory.createBevelBorder(1), "示例文本"));
        text.setFont(currentFont);
        text.setText("<html>生活就像海洋，只有意志坚强的人，才能到达彼岸。<br>This is an apple. I like apples. Apples are good for our health.</html>");
        exampleText.add(text);
        c.add(exampleText);
        JPanel buttonPanel = new JPanel();
        JPanel buttonPanelReal = new JPanel();
        buttonPanelReal.setLayout(new FlowLayout());
        buttonPanelReal.add(buttonApplyAll);
        buttonPanelReal.add(buttonApplyNow);
        buttonPanelReal.add(buttonCustomTTF);
        buttonPanelReal.add(buttonCancel);
        buttonPanel.setLayout(new BorderLayout());
        buttonPanel.add(buttonPanelReal, BorderLayout.EAST);
        c.add(buttonPanel);
        initEvents();
    }
    public FontFrame(WDTMain frame, boolean isNameAndStyleSettable) {
        super(frame);
        this.frame = frame;
        this.isNameAndStyleSettable = isNameAndStyleSettable;
        c.setLayout(new BoxLayout(c, BoxLayout.Y_AXIS));
        currentFont = ((CodeEdit) frame.getTabPane().getSelectedComponent()).getTextAreaFont();
        fontBase = ((CodeEdit) frame.getTabPane().getSelectedComponent()).getTextAreaFont();
        initialize();
    }
    public void showup() {
        setSize(800, 600);
        setTitle("字体设置");
        setVisible(true);
        setDefaultCloseOperation(2);
        setResizable(false);
    }
}